﻿using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace Web.Services
{
    public class Data : DataService<SaudoContext>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);
            // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
            config.UseVerboseErrors = true;
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }

        protected override SaudoContext CreateDataSource()
        {
            string connectionString = RoleEnvironment.GetConfigurationSettingValue("storage");
            CloudStorageAccount account = CloudStorageAccount.Parse(connectionString);

            CloudTableClient.CreateTablesFromModel(
                typeof(SaudoContext),
                account.TableEndpoint.AbsoluteUri,
                account.Credentials);

            return new SaudoContext(account.TableEndpoint.AbsoluteUri, account.Credentials);
        }
    }
}
